#include<termios.h>                                     
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include <string.h>

#include"interface.h"

static int ret = 0;
static int fd;
static int buf_size = 4;
ssize_t serial_recv_exact_nbytes(int fd, void *buf, size_t count)
{
	ssize_t ret;
	ssize_t total = 0;
	while (total != count) {
		ret = read(fd, buf + total, count - total);
		if (ret == -1) {
			perror("serial->recv");
			break;
		} else if (ret == 0) {
			fprintf(stdout, "serial->recv: timeout or end-of-file\n");
			break;
		} else
			total += ret;
	}
	return total;
}
void readbuf(char *readbuf)
{
	char *read_buf = readbuf;
	int i=0;
	ret = serial_recv_exact_nbytes(fd, read_buf, 4);
	if(0 > ret)
	{
		perror("read error:");
	}
}

int  conver(char *str,int nub)
{
	int i,j=0;
	int arr[nub];
	int sum=0;
	
	for(i=0;i<nub;i++)
	{
		if(str[i]==',')
			continue;
		arr[j++]=str[i]-'0';
		
	}
	i=j;
	for(j=0;j<i;j++)
	{
		sum+=arr[j];
		if(i>j+1)
			sum*=10;
	}
	return sum;
}

int get_obstacle(void)   //得到障碍物距离
{
	int distance;
	char read_buf[buf_size];
	bzero(read_buf,buf_size);
	fd = open("/dev/ttyUSB0", O_RDWR);//打开文件描述符
	if(fd < 0)
	{
		perror("open fd error!");
		return;
	}
	serial_init(fd);//初始化串口
	readbuf(read_buf);
	distance=conver(read_buf,buf_size);
	close(fd);
	return distance;
}
